﻿using System.Globalization;
using System.Numerics;

namespace InfluxDB.Flurl
{
    public class TimeUtils
    {
        private static readonly DateTime EpochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        private static BigInteger TimeSpanToBigInteger(TimeSpan timestamp, WritePrecision precision)
        {
            var time = precision switch
            {
                WritePrecision.Ns => (BigInteger)(timestamp.Ticks * 100),
                WritePrecision.Us => (BigInteger)(timestamp.Ticks * 0.1),
                WritePrecision.Ms => (BigInteger)timestamp.TotalMilliseconds,
                WritePrecision.S => (BigInteger)timestamp.TotalSeconds,
                _ => throw new ArgumentOutOfRangeException(nameof(precision), precision,
                                        "WritePrecision value is not supported"),
            };
            return time;
        }

        private static BigInteger DateTimeToBigInteger(DateTime timestamp, WritePrecision precision)
        {
            if (timestamp.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Timestamps must be specified as UTC", nameof(timestamp));
            }
            var timeSpan = timestamp.Subtract(EpochStart);
            return TimeSpanToBigInteger(timeSpan, precision);
        }

        private static BigInteger DateTimeOffsetToBigInteger(DateTimeOffset timestamp, WritePrecision precision)
        {
            return DateTimeToBigInteger(timestamp.UtcDateTime, precision);
        }

        public static string DateTimeToUtcString(DateTime timeUtc, WritePrecision precision)
        {
            var big = DateTimeToBigInteger(timeUtc, precision);
            return big.ToString(CultureInfo.InvariantCulture);
        }

        public static string DateTimeOffsetToUtcString(DateTimeOffset timeUtc, WritePrecision precision)
        {
            var big = DateTimeOffsetToBigInteger(timeUtc, precision);
            return big.ToString(CultureInfo.InvariantCulture);
        }

    }
}
